import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/config.dart';
import 'package:yp/config/index.dart';
import 'package:yp/helper.dart';
import 'package:yp/pages/mall_app/font_money_sale/state.dart';
import 'package:yp/services/api.dart';

class FontMoneySaleLogic extends GetxController {
  FontMoneySaleState state = FontMoneySaleState();
  var locationResult;
  Timer timer;
  Timer surplusTimer;

  @override
  void onInit() {
    super.onInit();
    locationResult = SpUtil.getObject(Config.USER_CURRENT_LOCATION);
    getFontMoneySale();
    startTimer();
  }

  @override
  void onClose() {
    super.onClose();
    timer?.cancel();
    timer = null;
    cancelTimer();
  }

  void getFontMoneySale() {
    var params = {
      // "data_sign": 0,
      "channel_num_id": 98,
      "use_platform": 3,
      "ec_shop_num_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
      "activity_id": Get.arguments['targetType']
    };
    Api.fontMoneySale(params).listen((event) {
      print('---------------------------');
      print(Get.arguments);
      print(params);
      print(event);
      print('---------------------------');

      if (event != null && event['code'] == 0) {
        state.catDetails = event['cat_details'] ?? []; // 分类列表
        state.catDetails.insert(0, {
          'cat1_id': 1666,
          'cat_name': '全部',
          'cat_ids': [],
        });
        state.configInfo = event['config_info'].split(","); // 配置
        print("state.configInfo: ${state.configInfo}");
        state.goodsList = event['goods_list']; // 商品列表
        DateTime time = DateTime.now();
        DateTime endTime = DateTime.parse(event['pre_end_time']).toUtc();
        Duration different = endTime.difference(time);
        state.surplusTime = different.inSeconds;
        startTimer();
      } else {
        toast(event != null ? event['message'] : '请求失败');
      }
    });
  }

  void startTimer() {
    // 设置 1 秒回调一次
    const period = const Duration(seconds: 1);
    surplusTimer = Timer.periodic(period, (timer) {
      if (state.surplusTime <= 0) {
        // 倒计时秒数为0，取消定时器
        print('我被取消了  ');
        cancelTimer();
        // getData();
      }
      //更新界面
      //秒数减一，因为一秒回调一次
      state.surplusTime--;
      // state.countContent = constructTime(state.surplusTime);
      state.surplusWidget = widgetConStructTime(state.surplusTime);
      update();
    });
  }

  void cancelTimer() {
    if (surplusTimer != null) {
      surplusTimer.cancel();
      surplusTimer = null;
    }
  }

  Widget _conStructCard(String data) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 3, vertical: 1),
      margin: const EdgeInsets.symmetric(horizontal: 4),
      decoration: BoxDecoration(
        color: EsColors.Primary,
        borderRadius: BorderRadius.circular(3),
      ),
      child: Text(
        data,
        style: TextStyle(
          color: const Color(0xffffffff),
        ),
      ),
    );
  }

  Widget widgetConStructTime(num mss) {
    int days = (mss / (60 * 60 * 24)).floor();
    int hours = ((mss % (60 * 60 * 24)) / (60 * 60)).floor();
    int minutes = ((mss % (60 * 60)) / 60).floor();
    int seconds = (mss % 60).floor();
    List timeList = [
      {'t': days, 'name': '天'},
      {'t': hours, 'name': '时'},
      {'t': minutes, 'name': '分'},
      {'t': seconds, 'name': '秒'},
    ];
    return Row(
      children: List.generate(
        timeList.length,
        (index) => Row(
          children: [
            _conStructCard(formatTime(timeList[index]['t']).toString() ?? '00'),
            Text(
              timeList[index]['name'],
              style: TextStyle(color: const Color(0xff999999), fontSize: 12),
            )
          ],
        ),
      ),
    );
  }

  String constructTime(double mss) {
    int days = (mss / (60 * 60 * 24)).floor();
    int hours = ((mss % (60 * 60 * 24)) / (60 * 60)).floor();
    int minutes = ((mss % (60 * 60)) / 60).floor();
    int seconds = (mss % 60).floor();
    return days.toString() +
        "天" +
        hours.toString() +
        "小时" +
        minutes.toString() +
        "分钟" +
        seconds.toString() +
        "秒";
  }

  String constructVipTime(int seconds) {
    int day = seconds % 1000 ~/ 3600 ~/ 24;
    int hour = seconds % 1000 ~/ 3600;
    int minute = seconds % 1000 % 3600 ~/ 60;
    int second = seconds % 1000 % 60;
    // if(day!= 0){
    //   return '剩$day天$hour小时$minute分';
    // }else if(hour!= 0){
    //   return '剩$hour小时$minute分';
    // }else if(minute!=0){
    //   return '剩$minute分';
    // }else {
    //   return '';
    // }
    return formatTime(day) +
        '天' +
        formatTime(hour) +
        "小时" +
        formatTime(minute) +
        "分" +
        formatTime(second);
  }

  // 数字格式化，将 0~9 的时间转换为 00~09
  String formatTime(int timeNum) {
    return timeNum < 10 ? "0" + timeNum.toString() : timeNum.toString();
  }
}
